package com.itfitness.mchart.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.widget.EaseImageView;
import com.itfitness.mchart.R;
import com.itfitness.mchart.factory.DialogFactory;
import com.itfitness.mchart.widget.SlideRecyclerView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class GroupActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.activity_group_rv)
    SlideRecyclerView activityGroupRv;
    @BindView(R.id.activity_group_rf)
    SwipeRefreshLayout activityGroupRf;
    private BaseQuickAdapter<EMGroup, BaseViewHolder> mBaseQuickAdapter;

    @Override
    protected int LayoutRes() {
        return R.layout.activity_group;
    }

    @Override
    protected boolean isHaveTitle() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initDatas();
    }

    private void initDatas() {
        setTitle("群组", R.color.colorTitleText);
        activityGroupRv.setLayoutManager(new LinearLayoutManager(this));
        activityGroupRf.setOnRefreshListener(this);
        initGroupList();
    }

    /**
     * 加载群组列表
     */
    private void initGroupList() {
        Observable.create(new ObservableOnSubscribe<List<EMGroup>>() {
            @Override
            public void subscribe(ObservableEmitter<List<EMGroup>> emitter) throws Exception {
                emitter.onNext(EMClient.getInstance().groupManager().getJoinedGroupsFromServer());
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<EMGroup>>() {
                    @Override
                    public void accept(List<EMGroup> groupList) throws Exception {
                        if (activityGroupRf.isRefreshing()) {
                            activityGroupRf.setRefreshing(false);
                        }
                        if (groupList != null && groupList.size() > 0) {
                            initAdapter(groupList);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (activityGroupRf.isRefreshing()) {
                            activityGroupRf.setRefreshing(false);
                        }
                        LogUtils.eTag("注册", throwable.getMessage());
                        ToastUtils.showShort("获取群列表失败");
                    }
                });
    }

    /**
     * 加载适配器数据
     *
     * @param groupList
     */
    private void initAdapter(List<EMGroup> groupList) {
        if (mBaseQuickAdapter == null) {
            mBaseQuickAdapter = new BaseQuickAdapter<EMGroup, BaseViewHolder>(R.layout.item_group_item, groupList) {
                @Override
                protected void convert(BaseViewHolder helper, EMGroup item) {
                    EaseImageView avatar = helper.getView(R.id.avatar);
                    TextView name = helper.getView(R.id.name);
                    avatar.setImageResource(R.drawable.em_group_icon);
                    name.setText(item.getGroupName());
                    if(item.getOwner().equals(EMClient.getInstance().getCurrentUser())){
                        helper.setText(R.id.tv_delete,"解散");
                    }else {
                        helper.setText(R.id.tv_delete,"退群");
                    }
                    helper.addOnClickListener(R.id.tv_delete);

                }
            };
            mBaseQuickAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                    String msg ;
                    final boolean isGroupOwner = mBaseQuickAdapter.getData().get(position).getOwner().equals(EMClient.getInstance().getCurrentUser());
                    if(isGroupOwner){
                        msg = "是否解散本群？";
                    }else {
                        msg = "是否退群？";
                    }
                    DialogFactory.createDefaultDialog(GroupActivity.this, msg, "确定", "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if(isGroupOwner){
                                destroyGroup(mBaseQuickAdapter.getData().get(position).getGroupId());
                            }else {
                                leaveGroup(dialog,mBaseQuickAdapter.getData().get(position).getGroupId());
                            }
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                }
            });
            mBaseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    EMGroup emGroup = mBaseQuickAdapter.getData().get(position);
                    Intent intent = new Intent(GroupActivity.this, ChartActivity.class);
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, emGroup.getGroupId());
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
                    startActivity(intent);
                }
            });
            activityGroupRv.setAdapter(mBaseQuickAdapter);
        } else {
            mBaseQuickAdapter.setNewData(groupList);
            mBaseQuickAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 解散群
     * @param groupId
     */
    private void destroyGroup(final String groupId) {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                EMClient.getInstance().groupManager().destroyGroup(groupId);//需异步处理
                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer == 1) {
                            ToastUtils.showShort("解散群成功");
                            activityGroupRv.closeMenu();
                            initGroupList();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("注册", throwable.getMessage());
                        ToastUtils.showShort("解散群失败，请重试");
                    }
                });
    }

    /**
     * 退群
     * @param dialog
     * @param groupId
     */
    private void leaveGroup(DialogInterface dialog, final String groupId) {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                EMClient.getInstance().groupManager().leaveGroup(groupId);//需异步处理
                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer == 1) {
                            ToastUtils.showShort("退群成功");
                            activityGroupRv.closeMenu();
                            initGroupList();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("注册", throwable.getMessage());
                        ToastUtils.showShort("退群失败，请重试");
                    }
                });
    }

    @Override
    public void onRefresh() {
        initGroupList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initGroupList();
    }

    @OnClick(R.id.activity_group_item_creategroup)
    public void onViewClicked() {
        //新建群组
        gotoActivity(NewGroupActivity.class);
    }
}
